package com.autosalon.app;

import org.hibernate.Session;

import com.autosalon.DaoCore.HibernateUtil;
import com.autosalon.model.Zakaznik;
import com.autosalon.ui.MainGuiWindow;
import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;
import com.vaadin.ui.Window;

public class AutosalonApp extends Application {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Zakaznik prihlasenyZakaznik;
	
	
	@Override
	public void init() {
		attachVaadinTransactionListener();
		Window mainWindow = new MainGuiWindow();
		setMainWindow(mainWindow);
		
	}

	// DON'T TOUCH THAT METHODS :)

	private void attachVaadinTransactionListener() {
		getContext().addTransactionListener(new TransactionListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void transactionEnd(Application application,
					Object transactionData) {
				if (application == AutosalonApp.this) {
					closeSession();
				}
			}

			@Override
			public void transactionStart(Application application,
					Object transactionData) {

			}
		});
	}

	private void closeSession() {
		Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
		if (sess.getTransaction().isActive()) {
			sess.getTransaction().commit();
		}
		if (sess.isOpen()) {
			sess.close();
		}
	}

	public Session getSession() {
		Session currentSession = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		if (!currentSession.getTransaction().isActive()) {
			currentSession.beginTransaction();
		}
		return currentSession;
	}

	public Zakaznik getPrihlasenyZakaznik() {
		return prihlasenyZakaznik;
	}

	public void setPrihlasenyZakaznik(Zakaznik prihlasenyZakaznik) {
		this.prihlasenyZakaznik = prihlasenyZakaznik;
	}
	
	

}
